<?php
namespace app\spadmin\controller\education;
use app\common\controller\Backend;
use think\Request;
/**
 * 广告位
 */
class Knowledge extends Backend{

    protected $subject = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Knowledge');
        $this->subject = model('Subject')->where('status',1)->order('sort asc')->column('id,name,id,sort');
        $this->view->assign('subject',$this->subject);
    }

    public function index(){
        $this->request->filter(['strip_tags', 'trim']);
        
        if($this->request->isAjax()){
            $data = $this->request->param();
            if (isset($data['keywords']) && $data['keywords']) {
                $map['title'] = ['like','%'.$data['keywords'].'%'];
            }
            if (isset($data['subject_id']) && $data['subject_id']) {
                $map['subject_id'] = $data['subject_id'];
            }
            if (isset($data['status']) && $data['status'] === '0') {
                $map['status'] = $data['status'];
            } else {
                $map['status'] = 1;
            }     
            $list =   $this->model->where($map)->order('sort asc')->paginate($data['limit'])->toArray();
            return $this->result($list);
        }
        return $this->view->fetch();
    }
    
    public function edit($ids = NULL){
        if($this->request->isPost()){
            $data = $this->request->post('',[],'strip_tags');
            $exam = [];
            if(isset($data['times']) && is_array($data['times'])){
                foreach ($data['times'] as $key => $value) {
                    $exam[$key]=[
                        'times'=>$value,
                        'answer'=>$data['answer'][$key],
                    ];
                }
            }
            Request::instance()->post(['exam'=>json_encode($exam),'times'=>null,'answer'=>null]);
        }
        return parent::edit($ids);
    }
    public function allow(){
        if($this->request->isPost()){
            $data = $this->request->param('',[],'strip_tags');
            $result = $this->model->whereIn('id',explode(',',$data['ids']))->update(['status'=>1]);
            if($result === false){
                $this->error($this->model->getError());
            }
            $this->success('启用成功');
        }
    }
    
    public function disabled(){
        if($this->request->isPost()){
            $data = $this->request->param('',[],'strip_tags');
            $result = $this->model->whereIn('id',explode(',',$data['ids']))->update(['status'=>0]);
            if($result === false){
                $this->error($this->model->getError());
            }
            $this->success('禁用成功');
        }
    }
}